package com.afs.electronicforensics.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import com.afs.electronicforensics.activity.R;
import com.afs.electronicforensics.activity.ShowActivity;
import com.afs.electronicforensics.utils.CheckPhone;
import com.afs.electronicforensics.utils.Constants;
import com.afs.electronicforensics.utils.SendCode;
import com.afs.electronicforensics.monitor.LoginMonitorEditText;
import com.afs.electronicforensics.utils.TimeCount;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class SignUpFragment extends Fragment {

    EditText username, password,phone,code;
    ConstraintLayout code_linearLayout;
    TextView sendCode,signup;
    //验证码倒计时
    private TimeCount time;
    float v=0;
    //设置注册请求网址
    String RegistrUrl = null;
    //手机号设置
    String tel = "";
    //验证码设置
    String word = "";
    //验证码设置
    char[] checkCode ={'0','1','2','3','4','5','6','7','8','9'};

    //自动登录
    SharedPreferences sp = null;


    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup root =(ViewGroup) inflater.inflate(R.layout.signup_fragment,container,false);

        sp = this.getActivity().getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        username =root.findViewById(R.id.user);
        password =root.findViewById(R.id.password);
        phone=root.findViewById(R.id.phone);
        code_linearLayout = root.findViewById(R.id.code_linearLayout);
        code=root.findViewById(R.id.code);
        sendCode = root.findViewById(R.id.send_code);
        time = new TimeCount(60000, 1000,sendCode);
        signup=root.findViewById(R.id.signup);

        username.setTranslationY(800);
        password.setTranslationY(800);
        phone.setTranslationY(800);
        code_linearLayout.setTranslationY(800);
        signup.setTranslationY(800);

        username.setAlpha(v);
        password.setAlpha(v);
        phone.setAlpha(v);
        code_linearLayout.setAlpha(v);
        signup.setAlpha(v);

        username.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(300).start();
        password.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(500).start();
        phone.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(700).start();
        code_linearLayout.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(700).start();
        signup.animate().translationY(0).alpha(1).setDuration(1000).setStartDelay(900).start();

        //EditText动态监测
        new LoginMonitorEditText().SetMonitorEditText(signup,username,password,phone,code);
        new LoginMonitorEditText().SetMonitorEditText(sendCode,phone);


        sendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String pNo = phone.getText().toString().trim();
                if(pNo.length()==0||pNo.equals("")){
                    Toast.makeText(getActivity(),"手机号码输入为空！",Toast.LENGTH_SHORT).show();
                }else if(!CheckPhone.isMobileNO(pNo)){
                    Toast.makeText(getActivity(),"手机号码格式有误！",Toast.LENGTH_SHORT).show();
                    phone.setText(null);
                }else{
                    String path = Constants.URL_ROOT+"user/findByPhone?phone="+pNo;//判断手机号码是否存在
                    new Verification().execute(path);
                }
            }
        });

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = username.getText().toString().trim();
                String pwd = password.getText().toString().trim();
                String mphone = phone.getText().toString().trim();
                String getCode = code.getText().toString().trim();
                if(getCode.equals(word)&&!word.equals("")){
                    /*Toast.makeText(getActivity(), "验证成功！", Toast.LENGTH_SHORT).show();*/
                    //跳转页面
                    RegistrUrl = Constants.URL_ROOT+"user/registerForAndroid"+"?password=" + pwd +
                            "&phone=" + mphone +"&userName=" + name;
                    new doRegister().execute(RegistrUrl);
                }else if(word.equals("")){
                    Toast.makeText(getActivity(), "未获取验证码！", Toast.LENGTH_SHORT).show();
                    code.setText(null);
                } else{
                    Toast.makeText(getActivity(), "验证码输入有误!", Toast.LENGTH_SHORT).show();
                    code.setText(null);
                }


            }
        });

        return root;
    }


    //发送验证码
    private class Verification extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");//这个应该都知道是干嘛的，默认是GET
                conn.setConnectTimeout(5000);

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            try {
                JSONObject js = new JSONObject(info);
                String result = js.getString("code").trim();
                if("1".equals(result)){
                    Toast.makeText(getActivity(), "该手机号码已被注册！", Toast.LENGTH_SHORT).show();
                    phone.setText(null);
                }else if("0".equals(result)){
                    time.start();
                    tel = phone.getText().toString().trim();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for(int i=0;i<4;i++){
                                word+=checkCode[(int)(checkCode.length*Math.random())];
                            }
                            SendCode sc = new SendCode();
                            String json = sc.bowlingJson(word,tel);
                            try{
                                sc.post("https://open.ucpaas.com/ol/sms/sendsms",json);
                                Looper.prepare();
                                Toast.makeText(getActivity(), "验证码已发送", Toast.LENGTH_SHORT).show();
                                Looper.loop();

                            }catch(IOException e) {
                                Looper.prepare();
                                Toast.makeText(getActivity(), "验证码发送失败", Toast.LENGTH_SHORT).show();
                                Looper.loop();
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    //判断注册
    private class  doRegister extends AsyncTask {

        @Override
        protected Object doInBackground(Object[] params) {

            String path = params[0].toString();

            try {
                //以get方式提交整个路径
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");//设置请求方式为get
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestProperty("Content-Type","application/json;charset=utf-8");
                conn.connect();

                if (conn.getResponseCode() == 200) {
                    InputStream is = conn.getInputStream();
                    BufferedReader br = new BufferedReader(new InputStreamReader(is));
                    String str = br.readLine();
                    return str;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            String info = o.toString().trim();
            try {
                JSONObject js = new JSONObject(info);
                String data = js.getString("data");
                JSONObject jsonData = new JSONObject(data);


            if("1".equals(js.getString("code"))){
                Toast.makeText(getActivity(), "注册成功！", Toast.LENGTH_SHORT).show();

                Constants.USER_ROOT.setUid(jsonData.getString("id"));
                Constants.USER_ROOT.setUsername(jsonData.getString("name"));
                Constants.USER_ROOT.setPassword(jsonData.getString("password"));
                Constants.USER_ROOT.setPhone(jsonData.getString("phone"));
                Constants.USER_ROOT.setUserAvatar(null);
                System.out.println(jsonData.getString("id"));
                //设置路径
                Constants.USER_PATH.setUserPath(jsonData.getString("id"));
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("ename", username.getText().toString().trim());
                editor.putString("epwd", password.getText().toString().trim());
                editor.putBoolean("autoLogin", true);
                editor.commit();


                Intent intent = new Intent();
                intent.setClass(getActivity(), ShowActivity.class);
                startActivity(intent);
                getActivity().finish();
            }else if("0".equals(js.getString("code"))){
                Toast.makeText(getActivity(), "用户名已被占用！", Toast.LENGTH_SHORT).show();
                username.setText(null);
            }else{
                Toast.makeText(getActivity(), "未知错误！注册失败！", Toast.LENGTH_SHORT).show();
            }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }



}
